package com.wk.springboot.service;

import com.meiin.base.core.exception.ApiException;
import com.wk.springboot.mp.ITestUserService;
import com.wk.springboot.mp.TestUser;
import com.wk.springboot.mp.TestUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class ScheduledServiceImpl implements ScheduledService{

    @Autowired
    TestUserServiceImpl iTestUserService;


    @Scheduled(cron = "${task.cron}")
    @Override
    public void scheduleGenDailyCheckRecord() {
        generateDailyCheckRecord(100);
    }

    /**
     * 事务流程参考这个方法 TransactionAspectSupport#invokeWithinTransaction
     *
     *
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateDailyCheckRecord(Integer day) {
        log.info("generateDailyCheckRecord {}", TransactionSynchronizationManager.getCurrentTransactionName());
        List<TestUser> objects1 = Lists.newArrayList();
        for (int i = 0;i<day;i++){
            TestUser testUser = new TestUser();
            testUser.setId(UUID.randomUUID().toString().replace("-",""));
            testUser.setName("zs");
            objects1.add(testUser);
        }
        iTestUserService.saveBatch(objects1);

        List<TestUser> objects2 = Lists.newArrayList();
        for (int i = 0;i<day;i++){
            TestUser testUser = new TestUser();
            testUser.setId(UUID.randomUUID().toString().replace("-",""));
            testUser.setName("ls");
            objects2.add(testUser);
        }
        iTestUserService.insertWithCustom(objects2);
        log.info("generateDailyCheckRecord#insertWithCustom {}", TransactionSynchronizationManager.getCurrentTransactionName());

//        iTestUserService.saveBatch(objects2);
//        throw new ApiException("1111");

    }
}
